package lumis.service.chatroom;

import java.util.Date;

import lumis.collaboration.chat.ChatConversationConfig;
import lumis.collaboration.chat.ChatManagerFactory;
import lumis.content.ContentException;
import lumis.doui.DouiStringResource;
import lumis.doui.processaction.ProcessActionHandler;
import lumis.portal.PortalException;
import lumis.util.IResource;

/**
 * Adds a chat conversation via chat manager.
 *
 * @version $Revision: 4482 $ $Date: 2006-09-18 18:33:56 -0300 (Mon, 18 Sep 2006) $
 * @since 4.0.6
 */
public class AddChatRoomProcessActionHandler extends ProcessActionHandler
{
	protected IResource chatRoomResource = new DouiStringResource();
	
	public AddChatRoomProcessActionHandler()
	{
		chatRoomResource.addResourcePath("lumis/service/chatroom/strings/strings");
	}
	
	@SuppressWarnings("unchecked")
	public void processAction() throws PortalException
	{
		ChatConversationConfig chatConversationConfig = new ChatConversationConfig();
	
		Date startTime = (Date)getParameter("startTime");
		chatConversationConfig.setStartTime(startTime);
		
		Date endTime = (Date)getParameter("endTime");
		if(endTime != null)
			chatConversationConfig.setEndTime(endTime);

		Integer userLimit = (Integer)getParameter("userLimit");
		if(userLimit != null)
			chatConversationConfig.setUserLimit(userLimit);
		
		
		Integer state = ChatConversationConfig.CHAT_CONVERSATION_STATE_ACTIVE;
		Date curTime = new Date();
		if(startTime.after(curTime))
			state = ChatConversationConfig.CHAT_CONVERSATION_STATE_WAITING;
		if(endTime != null && endTime.before(curTime))
			state = ChatConversationConfig.CHAT_CONVERSATION_STATE_INACTIVE;
		
		chatConversationConfig.setState(state);
		
		if((Boolean)getParameter("moderated"))
		{
			String moderator = (String)getParameter("moderator", String.class);
			
			if(moderator == null)
				throw new ContentException("STR_MODERATOR_NOT_SPECIFIED", chatRoomResource);
			
			chatConversationConfig.setModerated(true);
			chatConversationConfig.setModerator(moderator);
		}
		
		ChatManagerFactory.getChatManager().addConversation(sessionConfig, chatConversationConfig, transaction);
		
		douiContext.getActionResponse().setRenderParameter("chatConversationId", chatConversationConfig.getId());
		douiContext.getActionResponse().setRenderParameter("state", state.toString());
		
		addDefaultResponse();
	}
}
